package com.iweipan.fragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.iweipan.R;
import com.iweipan.activity.MoneyActivity;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;

import static com.iweipan.base.WPUrlBase.WP_CREATE_ORDER;

/**
 * Created by Administrator on 2016/11/22.
 */

public class BuyDialogFragment extends DialogFragment {


    @BindView(R.id.button)
    ImageView button;
    @BindView(R.id.money)
    RadioButton money;
    @BindView(R.id.system)
    RadioButton system;
    @BindView(R.id.one)
    RelativeLayout one;
    @BindView(R.id.two)
    RelativeLayout two;
    @BindView(R.id.three)
    RelativeLayout three;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.time_down)
    TextView timeDown;
    @BindView(R.id.time)
    TextView time;
    @BindView(R.id.time_up)
    TextView timeUp;
    @BindView(R.id.up_down)
    TextView upDown;
    @BindView(R.id.up)
    TextView up;
    @BindView(R.id.up_up)
    TextView upUp;
    @BindView(R.id.down_down)
    TextView downDown;
    @BindView(R.id.down)
    TextView down;
    @BindView(R.id.down_up)
    TextView downUp;
    @BindView(R.id.buy_text)
    TextView buyText;
    @BindView(R.id.buy_money)
    TextView buyMoney;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.fee)
    TextView fee;
    @BindView(R.id.title_frame)
    FrameLayout titleFrame;

    public final static int BUY_UP = 2;
    public final static int BUY_DOWN = 1;
    private double myMoney;
    private MyBundle addNum;
    private int buy;
    private int createType = 0;
    private int juanType = 0;
    private String token;
    private boolean isMoney = true;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NO_TITLE, android.R.style.Theme_Holo_Light_Dialog_MinWidth);

    }

    public static BuyDialogFragment newInstance(int buy, double myMoney, MyBundle addNum, String token) {

        Bundle args = new Bundle();
        args.putInt("buy", buy);
        args.putDouble("myMoney", myMoney);
        args.putSerializable("addNum", addNum);
        args.putString("token", token);
        BuyDialogFragment fragment = new BuyDialogFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_buy, null);
        getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        getDialog().setCanceledOnTouchOutside(false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onStart() {
        super.onStart();
        doSomeThing();
    }

    private void doSomeThing() {
        Bundle arguments = getArguments();
        buy = arguments.getInt("buy");
        myMoney = arguments.getDouble("myMoney");
        token = arguments.getString("token");
        addNum = (MyBundle) arguments.getSerializable("addNum");


        switch (buy) {
            case BUY_DOWN:
                titleFrame.setBackgroundResource(R.drawable.buy_dialog_title_down_bg);
                titleText.setText("买跌");
                break;
            case BUY_UP:
                titleFrame.setBackgroundResource(R.drawable.buy_dialog_title_up_bg);
                titleText.setText("买涨");
                break;
        }
        createType = 4;
        juanType = 4;
        setBuyText(8, 1, 1);

        radioGroup.check(money.getId());
        one.callOnClick();

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == money.getId()) {
                    isMoney = true;
                    one.callOnClick();

                } else if (checkedId == system.getId()) {
                    isMoney = false;
                    one.callOnClick();
                }

            }
        });

    }

    @OnClick({R.id.button, R.id.one, R.id.buy_text, R.id.two, R.id.three, R.id.time_down, R.id.time_up, R.id.up_down, R.id.up_up, R.id.down_down, R.id.down_up})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button:
                dismiss();
                Handler handle = addNum.getHandler();
                handle.sendEmptyMessage(1);
                break;
            case R.id.buy_text:
                if (buyText.getText().toString().equals("购买")) {
                    if (isMoney) {
                        createOrder(0);
                    } else {
                        createOrder(1);
                    }
                    dismiss();
                } else if (buyText.getText().toString().equals("余额不足请充值")) {
                    Intent intent = new Intent(getContext(), MoneyActivity.class);
                    intent.putExtra("token",token);
                    intent.putExtra("myMoney",myMoney);
                    startActivity(intent);
                    dismiss();

                } else if (buyText.getText().toString().equals("银圆券数量不足")) {

                }


//                dismiss();
                break;
            case R.id.one:
                one.setSelected(true);
                two.setSelected(false);
                three.setSelected(false);
                buyMoney.setText("¥8");
                setBuyText(8, 1, 1);
                createType = 4;
                juanType = 1;
                time.setText("1");
                break;
            case R.id.two:
                one.setSelected(false);
                two.setSelected(true);
                three.setSelected(false);
                buyMoney.setText("¥80");
                setBuyText(80, 2, 1);
                createType = 10;
                juanType = 2;
                time.setText("1");
                break;
            case R.id.three:
                one.setSelected(false);
                two.setSelected(false);
                three.setSelected(true);
                buyMoney.setText("¥200");
                setBuyText(200, 3, 1);
                createType = 11;
                juanType = 3;
                time.setText("1");
                break;
            case R.id.time_down:
                changeTime(2);
                break;
            case R.id.time_up:
                changeTime(1);
                break;
            case R.id.up_down:
                changeListen(2, 0);
                break;
            case R.id.up_up:
                changeListen(1, 0);
                break;
            case R.id.down_down:
                changeListen(2, 1);
                break;
            case R.id.down_up:
                changeListen(1, 1);
                break;
        }
    }

    private void createOrder(int isJuan) {
        JSONObject creatJson = new JSONObject();
        try {
            creatJson.put("productId", createType);
            creatJson.put("type", buy);
            creatJson.put("sl", time.getText().toString());
            creatJson.put("isJuan", isJuan);
            creatJson.put("token", token);
            if (isJuan == 1) {
                creatJson.put("juanno", time.getText().toString());
                creatJson.put("couponId", juanType);
            }
            creatJson.put("toplimit", Integer.parseInt(up.getText().toString()) * 1.0 / 100 + "");
            creatJson.put("bottomlimit", Integer.parseInt(down.getText().toString()) * 1.0 / 100 + "");
//            Log.e("BuyDialogFragment", creatJson.toString());
            OkHttpUtils.get()
                    .url(WP_CREATE_ORDER)
                    .addParams("p", creatJson.toString())
                    .build()
                    .execute(new StringCallback() {
                        @Override
                        public void onError(Call call, Exception e, int id) {

                        }

                        @Override
                        public void onResponse(String response, int id) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                String code = jsonObject.getString("code");
                                if (code.equals("200")) {
//                                    Log.e("BuyDialogFragment", "createOrder" + response);
                                    Handler handler = addNum.getHandler();
                                    handler.sendEmptyMessage(1);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }


    }

    private void setBuyText(int goToBuy, int type, int timeInt) {
        int addMoney = goToBuy * timeInt;
        double feeAdd = 0;
        if (isMoney) {
            if (goToBuy == 8) {
                feeAdd = 0.6 * timeInt;
            } else if (goToBuy == 80) {
                feeAdd = 6 * timeInt;

            } else if (goToBuy == 200) {
                feeAdd = 24 * timeInt;
            } else {
                return;
            }
            java.text.DecimalFormat df = new java.text.DecimalFormat("#.##");

            fee.setText(df.format(feeAdd));

            if (myMoney >= addMoney + feeAdd) {
                buyText.setText("购买");
                buyText.setTextColor(Color.parseColor("#ffa800"));
            } else {
                buyText.setText("余额不足请充值");
                buyText.setTextColor(Color.parseColor("#ffa800"));
            }
        } else {
            fee.setText("0");
            HashMap<Integer, Integer> numMap = addNum.getNumMap();
            int yinyuanquanNum = 0;
            if (numMap != null && numMap.size() > 0) {
                try {
                    int num = numMap.get(type);
                    if (type == 1) {
                        yinyuanquanNum = num * 8;
                    }
                    if (type == 2) {
                        yinyuanquanNum = num * 80;
                    }
                    if (type == 3) {
                        yinyuanquanNum = num * 200;
                    }

                    if (yinyuanquanNum >= addMoney) {
                        buyText.setText("购买");
                        buyText.setTextColor(Color.parseColor("#ffa800"));
                    } else {
                        buyText.setText("银圆券数量不足");
                        buyText.setTextColor(Color.parseColor("#ffa800"));
                    }
                } catch (Exception e) {
                    buyText.setText("银圆券数量不足");
                    buyText.setTextColor(Color.parseColor("#ffa800"));
                }

            } else {
                buyText.setText("银圆券数量不足");
                buyText.setTextColor(Color.parseColor("#ffa800"));
            }


        }

    }

    private void changeTime(int type) {
        int timeInt = Integer.parseInt(time.getText().toString());
        boolean oneSele = one.isSelected();
        boolean twoSele = two.isSelected();
        boolean threeSele = three.isSelected();

        if (type == 1) {
            if (timeInt >= 10) {
                return;
            }
            timeInt++;
            if (oneSele) {
                buyMoney.setText("¥" + 8 * timeInt);
                setBuyText(8, 1, timeInt);
            }

            if (twoSele) {
                buyMoney.setText("¥" + 80 * timeInt);
                setBuyText(80, 2, timeInt);
            }

            if (threeSele) {
                buyMoney.setText("¥" + 200 * timeInt);
                setBuyText(200, 3, timeInt);
            }


            time.setText(timeInt + "");
        } else {
            if (timeInt == 1) {
                return;
            }
            timeInt--;
            if (oneSele) {
                buyMoney.setText("¥" + 8 * timeInt);
                setBuyText(8, 1, timeInt);
            }

            if (twoSele) {
                buyMoney.setText("¥" + 80 * timeInt);
                setBuyText(80, 2, timeInt);
            }

            if (threeSele) {
                buyMoney.setText("¥" + 200 * timeInt);
                setBuyText(200, 3, timeInt);
            }

            time.setText(timeInt + "");

        }

    }


    private void changeListen(int type, int listenType) {
        TextView[] textViews = {up, down};
        int timeInt = Integer.parseInt(textViews[listenType].getText().toString());
        if (type == 1) {
            if (timeInt >= 50) {
                return;
            }
            timeInt += 10;
            textViews[listenType].setText(timeInt + "");
        } else {
            if (timeInt == 0) {
                return;
            }
            timeInt -= 10;
            textViews[listenType].setText(timeInt + "");

        }

    }

}
